// ==UserScript==
// @name		Pardus Clocker
// @namespace	PardusClocker
// @include		http://*.pardus.at/*
// ==/UserScript==

/**
 * Current Version: 0.6.2
 *
 * Release Notes:
 *
 * 0.6.2 ()
 * - fixed some formatting issues
 * - created settings var and moved in the get/set functions
 * - shortcut key 't' for building/starbase/planet trade added
 * 0.6.1 (5/8/2008)
 * - shortcut keys should work on all frames now.
 * - rearranged code a bit
 */


var maxAPMinLeft = 0;

// BEGIN Shortcut Class
function Shortcut(key, name) {
    this.key = key;
    this.name = name;
};
Shortcut.prototype.key;
Shortcut.prototype.name;
Shortcut.prototype._page; // Can be null, '' or have a value. 
Shortcut.prototype.page = function () {
    if (this._page == null) {
        this._page = this.getPage();
        if (this._page == null) this._page = '';
        return this._page;
    }
    else return this._page;
};
Shortcut.prototype.navigateToPage = function() {
    if (this.page()) // if it is not null or empty
        top.frames[2].location.href = this.page();
};
Shortcut.prototype.toString = function() {
    return this.page();
};
Shortcut.prototype.getPage = function() {
    // MUST BE OVERWRITTEN
    return 'main.php';
};
// END Shortcut Class

// BEGIN ShortcutCollection Class
function ShortcutCollection() {
    this.shortcuts = [];
};
ShortcutCollection.prototype.shortcuts;
ShortcutCollection.prototype.length = function() {
    if (this.shortcuts.length > 0) return this.shortcuts.length;
    else return 0;
};
ShortcutCollection.prototype.add = function(shortcut) {
    this.shortcuts.push(shortcut);
};
ShortcutCollection.prototype.actOnKey = function(key) {
    if (!this.shortcuts) return;
    for (var i = 0, len = this.shortcuts.length; i < len; i++) {
        if (this.shortcuts[i].key == key) {
            this.shortcuts[i].navigateToPage();
            break;
        }
    }
}; 
ShortcutCollection.prototype.getActiveKeyDescriptions = function() {
    var descriptions = [];
    for (var i = 0, len = this.shortcuts.length; i < len; i++) {
        if (this.shortcuts[i].page()) { // if this shortcut's page isn't null or empty
            descriptions.push(this.shortcuts[i].key + ' = ' + this.shortcuts[i].name);
        }
    }
    return descriptions;
};
// END ShortcutCollection Class

// SETTINGS!
var settings = {
    'currentUniverse': function() {
        if(/orion/.test(location)) return "orion";
        else if(/pegasus/.test(location)) return "pegasus";
        else if(/artemis/.test(location)) return "artemis";
        else return "";
    },
    
    '_shortcutCollection': new ShortcutCollection(),
    'shortcutCollection': function() {
        if (settings._shortcutCollection.length() < 1) {
            var s;
            s = new Shortcut('N', 'Nav');
            s.getPage = function() { return 'main.php'; };
            settings._shortcutCollection.add(s);
			
            s = new Shortcut('S', 'Overview Stats');
            s.getPage = function() { return 'overview_stats.php'; };
            settings._shortcutCollection.add(s);
			
            s = new Shortcut('B', 'Overview Buildings');
            s.getPage = function() { return 'overview_buildings.php'; };
            settings._shortcutCollection.add(s);
			
            s = new Shortcut('R', 'Repair');
            s.getPage = function() { 
                if (main.onPlanet() || main.onStarbase()) return 'ship_equipment.php'; 
            }; settings._shortcutCollection.add(s);
			
            s = new Shortcut('T', 'Trade');
            s.getPage = function () {
                if (main.onBuilding()) return 'building_trade.php';
                else if (main.onPlanet()) return 'planet_trade.php';
                else if (main.onStarbase()) return 'starbase_trade.php';
            }; settings._shortcutCollection.add(s);

            s = new Shortcut('V', 'Visit');
            s.getPage = function () {
                if (main.onBuilding()) return 'building.php';
                else if (main.onPlanet()) return 'planet.php';
                else if (main.onStarbase()) return 'starbase.php';
            }; settings._shortcutCollection.add(s);
        }
			
        return settings._shortcutCollection;
    },
    
    //current pilot stats
    'pilot': {
        'ap': {
            'get': function() { return parseInt(GM_getValue(settings.currentUniverse() + "." + "pilotAP", 0)); },
            'set': function(value) { GM_setValue(settings.currentUniverse() + "." + "pilotAP", value); }
        },
        'maxAP': {
            'get': function() { return parseInt(GM_getValue(settings.currentUniverse() + "." + "pilotMaxAP", 5000)); },
            'set': function(value) { GM_setValue(settings.currentUniverse() + "." + "pilotMaxAP", value); }
        },
        'exp': 0,
        'tac': {
            'base': 0,
            'actual': 0,
            'turnin': 65,
            'turninDist': function() {
                return (this.base - this.turnin).toFixed(2);
            },
            'overskill': function() { //Tactics: 32 + 13.1 per 100k exp
                return (32 + 13.1 * (settings.pilot.exp / 100000)).toFixed(2);
            },
            'overskillDist': function() {
                return (this.base - this.overskill()).toFixed(2);
            }
        },
        'hit': {
            'base': 0,
            'actual': 0,
            'turnin': 70,
            'turninDist': function() {
                return (this.base - this.turnin).toFixed(2);
            },
            'overskill': function() { //Hit accuracy: 42 +13.1 per 100k exp
                return (42 + 13.1 * (settings.pilot.exp / 100000)).toFixed(2);
            },
            'overskillDist': function() {
                return (this.base - this.overskill()).toFixed(2);
            }
        },
        'man': {
            'base': 0,
            'actual': 0,
            'turnin': 65,
            'turninDist': function() {
                return (this.base - this.turnin).toFixed(2);
            },
            'overskill': function() { //Maneuver skill: 32 + 13.1 per 100k exp
                return (32 + 13.1 * (settings.pilot.exp / 100000)).toFixed(2);
            },
            'overskillDist': function() {
                return (this.base - this.overskill()).toFixed(2);
            }
        },
        'wep': {
            'base': 0,
            'actual': 0,
            'turnin': 40,
            'turninDist': function() {
                return (this.base - this.turnin).toFixed(2);
            },
            'overskill': function() { //Weaponry skill: 20 + 13.1 per 100k exp
                return (20 + 13.1 * (settings.pilot.exp / 100000)).toFixed(2);
            },
            'overskillDist': function() {
                return (this.base - this.overskill()).toFixed(2);
            }
        },
        'eng': {
            'base': 0,
            'actual': 0,
            'turnin': 33,
            'turninDist': function() {
                return (this.base - this.turnin).toFixed(2);
            },
            'overskill': function() { //Engineering: 15 + 13.1 per 100k exp
                return (15 + 13.1 * (settings.pilot.exp / 100000)).toFixed(2);
            },
            'overskillDist': function() {
                return (this.base - this.overskill()).toFixed(2);
            }
        }
    },
    
    //pilot stats for asp gain (most are set when the "reset" button is clicked
    'pilotAsp': {
        'skillView': {
            'get': function() { return GM_getValue(settings.currentUniverse() + "." + "pilotSkillView", 0); },
            'set': function(value) { GM_setValue(settings.currentUniverse() + "." + "pilotSkillView", value); }
        },
        'tac': {
            'get': function(value) { return GM_getValue(settings.currentUniverse() + "." + "pilotAspTac", value); },
            'getFloat': function() { return parseFloat(this.get()); },
            'set': function(value) { GM_setValue(settings.currentUniverse() + "." + "pilotAspTac", value); },
            'aspGain': function() {return((settings.pilot.tac.base - this.get(settings.pilot.tac.base))*.8).toFixed(2);}
        },
        'hit': {
            'get': function(value) { return GM_getValue(settings.currentUniverse() + "." + "pilotAspHit", value); },
            'getFloat': function() { return parseFloat(this.get()); },
            'set': function(value) { GM_setValue(settings.currentUniverse() + "." + "pilotAspHit", value); },
            'aspGain': function() {return((settings.pilot.hit.base - this.get(settings.pilot.hit.base))*.8).toFixed(2);}
        },
        'man': {
            'get': function(value) { return GM_getValue(settings.currentUniverse() + "." + "pilotAspMan", value); },
            'getFloat': function() { return parseFloat(this.get()); },
            'set': function(value) { GM_setValue(settings.currentUniverse() + "." + "pilotAspMan", value); },
            'aspGain': function() {return((settings.pilot.man.base - this.get(settings.pilot.man.base))*.8).toFixed(2);}
        },
        'wep': {
            'get': function(value) { return GM_getValue(settings.currentUniverse() + "." + "pilotAspWep", value); },
            'getFloat': function() { return parseFloat(this.get()); },
            'set': function(value) { GM_setValue(settings.currentUniverse() + "." + "pilotAspWep", value); },
            'aspGain': function() {return((settings.pilot.wep.base - this.get(settings.pilot.wep.base))*1.6).toFixed(2);}
        },
        'eng': {
            'get': function(value) { return GM_getValue(settings.currentUniverse() + "." + "pilotAspEng", value); },
            'getFloat': function() { return parseFloat(this.get()); },
            'set': function(value) { GM_setValue(settings.currentUniverse() + "." + "pilotAspEng", value); },
            'aspGain': function() {return((settings.pilot.eng.base - this.get(settings.pilot.eng.base))*2).toFixed(2);}
        },
        'ap': {
            'get': function(value) { return parseInt(GM_getValue(settings.currentUniverse() + "." + "pilotAspAP", value)); },
            'set': function(value) { GM_setValue(settings.currentUniverse() + "." + "pilotAspAP", value); }
        },
        
        'apUsedPerDay': function() {return 5760/(settings.pilot.ap.get()-settings.pilotAsp.ap.get(settings.pilot.ap.get()));},
        'totalAspPerDay': function() {
            var str = "Total ASP/Day: ";
            var totalaspgain = parseFloat(settings.pilotAsp.tac.aspGain())+parseFloat(settings.pilotAsp.hit.aspGain())+parseFloat(settings.pilotAsp.man.aspGain())+parseFloat(settings.pilotAsp.wep.aspGain())+parseFloat(settings.pilotAsp.eng.aspGain());
            return str+(settings.pilotAsp.apUsedPerDay()*totalaspgain).toFixed(2);
        }
    },  

    'testStats': function (skill) {
        GM_log("base:"+skill.base+" actual:"+skill.actual+" turnin:"+skill.turnin+" tdist:"+skill.turninDist()+" overskill:"+skill.overskill()+" oDist:"+skill.overskillDist());
    },
	
    'html': {
        'parent': function () {return top.document.body.innerHTML; },
        'nav': function () { return top.frames[0].document.body.innerHTML; },
        'msgframe': function () { return top.frames[1].document.body.innerHTML; },
        'main': function () { return top.frames[2].document.body.innerHTML; }
    }
};

// END SETTINGS!

// MAIN FRAME
var main = {
    'html': function () { return top.frames[2].document.body.innerHTML; },
    'location': function () { return top.frames[2].location; },
	
    'pageIsNav': function () { return /main\.php/.test(main.location()); },
	
    'pageIsShip_equipment': function () { return /ship_equipment\.php/.test(main.location()); },
    'pageIsBulletin_board': function () { return /bulletin_board\.php/.test(main.location()); },
    'pageIsBounties': function () { return /bounties\.php/.test(main.location()); },
    'pageIsBounty_place': function () { return /bounty_place\.php/.test(main.location()); },
    'pageIsBounty_mostwanted': function () { return /bounty_mostwanted\.php/.test(main.location()); },
	
    'pageIsPlanet': function () { return /planet\.php/.test(main.location()); },
    'pageIsPlanet_trade': function () { return /planet_trade\.php/.test(main.location()); },
	
    'pageIsStarbase': function () { return /starbase\.php/.test(main.location()); },
    'pageIsStarbase_trade': function () { return /starbase_trade\.php/.test(main.location()); },
	
    'onBuilding': function () {
        if (main.pageIsNav())
            if (/href=.building\.php/.test(main.html())) // here the . matches a '.  Matching the ' wasn't working.
                return true;
		
        return false;
    },
    'onPlanet': function () { 
        if (main.pageIsNav())
            if (/planet\.php/.test(main.html()))
                return true;
        else if (main.pageIsPlanet() || main.pageIsPlanet_trade())
            return true;
        else if (main.pageIsShip_equipment() || main.pageIsBulletin_board() || main.pageIsBounties() || main.pageIsBounty_place() || main.pageIsBounty_mostwanted())
            if (/planet\.php/.test(main.html()))
                return true;
		
        return false;
    },
    'onStarbase': function () { 
        if (main.pageIsNav())
            if (/starbase\.php/.test(main.html()))
                return true;
        else if (main.pageIsStarbase() || main.pageIsStarbase_trade())
            return true;
        else if (main.pageIsShip_equipment() || main.pageIsBulletin_board() || main.pageIsBounties() || main.pageIsBounty_place() || main.pageIsBounty_mostwanted())
            if (/starbase\.php/.test(main.html()))
                return true;
		
        return false;
    }
};
// END MAIN FRAME

/* Question Mark code
var descs = settings.shortcutCollection().getActiveKeyDescriptions();
for (var i = 0; i < descs.length; i++) {
	GM_log(descs[i]);
}
 */

//GM_log(main.location());
//GM_log(/main\.php/.test(main.location()));
//GM_log('Page is nav: ' + main.pageIsNav());

if (/main/.test(location))
{
    setupMain();
}
else if (/overview_stats/.test(location))
{
    setupStats();
}
else if (/ship2opponent/.test(location))
{
    setupNPCCombat();
}
else if (/logout/.test(location))
{
    setupDocked();
}
setupShortcuts();

function setupMain()
{
    var tables = document.body.getElementsByTagName("table");
    //time above nav
    var navTimeDiv = document.createElement("div");
    navTimeDiv.innerHTML = '<div style="width:100%;">' +
        '<table border="0" width="500px" align="center" style="font-size:11px;">' +
        '<tr>' +
        '<td>Time: <span id="tim">08:13:55</span></td>' +
        '<td>GMT: <span id="gmt">06:13:55</span></td>' +
        '<td>AP: <span id="ap">00:04:04</span></td>' +
        '<td>B: <span id="bui">03:11:04</span></td>' +
        '<td>P: <span id="pl">01:11:04</span></td>' +
        '<td>S: <span id="sb">02:11:04</span></td>' +
        '</tr>' +
        '</table>' +
        '</div>';

    var nav = tables[0].rows[0].cells[1];
    nav.insertBefore(navTimeDiv, nav.childNodes[0]);


    //max ap clock
    var maxAPCell = document.createElement("td");
    maxAPCell.colSpan = 4;
    maxAPCell.align = "center";
    maxAPCell.innerHTML = '<span style="font-size:10;">Max AP:&nbsp;&nbsp;<span id="maxAP">00:05:15</span></span>';
    var maxAPRow = document.createElement("tr");
    maxAPRow.vAlign = "center";
    maxAPRow.appendChild(maxAPCell);
    tables[2].childNodes[0].insertBefore(maxAPRow, tables[2].rows[4]);

    //GM_log(settings.pilot.maxAP.get());
    maxAPMinLeft = (Math.ceil((settings.pilot.maxAP.get()-parseInt(tables[2].rows[0].cells[2].textContent))/24)*6)-((new Date).getMinutes()%6)-1;

    //nav cell border
    for(var i = 1; i < tables.length; i++)
    {
        if(tables[i].width == 448)
        {
            tables[i].cellSpacing = 1;
            tables[i].bgColor = "333333";
        }
    }

    StartClock();
}

function setupStats()
{
    var tables = document.body.getElementsByTagName("table");
    var tds = tables[6].getElementsByTagName("td");
    for(var i = 0; i < tds.length; i++)
    {
        if(tds[i].textContent.indexOf("Experience:") != -1)
        {
            var exp = tds[i+1].textContent;
            while(/,/.test(exp))
            {
                exp = exp.replace(/,/, '');
            }
            settings.pilot.exp = parseInt(exp);
            //GM_log("Exp: "+exp);
        }
        else if(tds[i].textContent.indexOf("Maximum APs:") != -1)
        {
            var apStr = tds[i+1].textContent;
            var index = apStr.indexOf("+");
            if(index == -1)
            {
                settings.pilot.maxAP.set(parseInt(apStr));
            }
            else //supports meditation
            {
                settings.pilot.maxAP.set(parseInt(apStr.substr(0,index)) + parseInt(apStr.substr(index+1, apStr.length)));
            }
            //GM_log("Max AP: "+settings.pilot.maxAP.get());
        }
        else if(tds[i].textContent.indexOf("APs played:") != -1)
        {
            var aps = tds[i+1].textContent;
            while(/,/.test(aps))
            {
                aps = aps.replace(/,/, '');
            }
            settings.pilot.ap.set(aps);
            //GM_log("APs Played: "+settings.pilot.ap.get());
        }
        else
        {
            //GM_log(tds[i].textContent);
        }
    }
    
    var expSkill = 13.1 * (settings.pilot.exp / 100000);
    var statsTable = tables[5].rows[0].cells[1].getElementsByTagName("table")[0];
    
    //parse skills
    settings.pilot.tac.base = statsTable.rows[6].cells[1].textContent;
    settings.pilot.tac.actual = statsTable.rows[6].cells[2].innerHTML.replace(/"/g,"");
    settings.pilot.hit.base = statsTable.rows[7].cells[1].textContent;
    settings.pilot.hit.actual = statsTable.rows[7].cells[2].innerHTML.replace(/"/g,"");
    settings.pilot.man.base = statsTable.rows[8].cells[1].textContent;
    settings.pilot.man.actual = statsTable.rows[8].cells[2].innerHTML.replace(/"/g,"");
    settings.pilot.wep.base = statsTable.rows[9].cells[1].textContent;
    settings.pilot.wep.actual = statsTable.rows[9].cells[2].innerHTML.replace(/"/g,"");
    settings.pilot.eng.base = statsTable.rows[10].cells[1].textContent;
    settings.pilot.eng.actual = statsTable.rows[10].cells[2].innerHTML.replace(/"/g,"");

    //stat switch dropdown
    var statSwitch = document.createElement("select");
    statSwitch.style.cssText = "cursor: pointer; color: rgb(255, 204, 17);";
    statSwitch.options.add(new Option("Actual", "0"));
    statSwitch.options.add(new Option("Overskill", "1"));
    statSwitch.options.add(new Option("Turn-In", "2"));
    statSwitch.options.add(new Option("ASPs", "3"));
    statSwitch.addEventListener('change',
    function(event) {
        settings.pilotAsp.skillView.set(this.selectedIndex);
        setStatSwitch(event.target);
    }, false);
    statsTable.rows[5].cells[2].colSpan = 2;
    statsTable.rows[5].cells[2].align = "left";
    statsTable.rows[5].cells[2].appendChild(statSwitch);

    //reset button
    var resetAsp = document.createElement("input");
    resetAsp.id = "resetAspButton";
    resetAsp.type = "button";
    resetAsp.value = "Reset";
    resetAsp.style.cssText = "color: rgb(255, 204, 17); font-size: 10px; width: 40;";
    resetAsp.addEventListener('click',
    function(event) {
        var tbl = event.target.parentNode.parentNode.parentNode.parentNode;
        settings.pilotAsp.tac.set(settings.pilot.tac.base);
        settings.pilotAsp.hit.set(settings.pilot.hit.base);
        settings.pilotAsp.man.set(settings.pilot.man.base);
        settings.pilotAsp.wep.set(settings.pilot.wep.base);
        settings.pilotAsp.eng.set(settings.pilot.eng.base);
        settings.pilotAsp.ap.set(settings.pilot.ap.get());
        tbl.rows[6].cells[2].textContent = "0.00";
        tbl.rows[7].cells[2].textContent = "0.00";
        tbl.rows[8].cells[2].textContent = "0.00";
        tbl.rows[9].cells[2].textContent = "0.00";
        tbl.rows[10].cells[2].textContent = "0.00";
    }, false);
    statsTable.rows[11].cells[2].appendChild(resetAsp);

    setStatSwitch(statSwitch);

    //statsTable.rows[5].cells[1].align = "right";
    var statusStrOld =  "<a style='cursor: pointer;' onmouseover='dict_descriptions[\"Overskill\"] = \"" +
        "<table>" +
        "<tr><td width=65>Tactics:</td><td width=45>" + (parseFloat(statsTable.rows[6].cells[1].textContent) - (32 + expSkill)).toFixed(2) + "</td><td>" + (32 + expSkill).toFixed(2) + "</td></tr>" +
        "<tr><td>Hit Acc:</td><td>" + (parseFloat(statsTable.rows[7].cells[1].textContent) - (42 + expSkill)).toFixed(2) + "</td><td>" + (42 + expSkill).toFixed(2) + "</td></tr>" +
        "<tr><td>Maneuver:</td><td>" + (parseFloat(statsTable.rows[8].cells[1].textContent) - (32 + expSkill)).toFixed(2) + "</td><td>" + (32 + expSkill).toFixed(2) + "</td></tr>" +
        "<tr><td>Weaponry:</td><td>" + (parseFloat(statsTable.rows[9].cells[1].textContent) - (20 + expSkill)).toFixed(2) + "</td><td>" + (20 + expSkill).toFixed(2) + "</td></tr>" +
        "<tr><td>Eng:</td><td>" + (parseFloat(statsTable.rows[10].cells[1].textContent) - (15 + expSkill)).toFixed(2) + "</td><td>" + (15 + expSkill).toFixed(2) + "</td></tr>" +
        "</table>" +
        "\"; tip(this,\"Overskill\",\"Overskill\", \"r\");' onmouseout='nukeTip();' onclick='return false;'>" +
        "<font color='#ffcc11'>O</font></a>" +
        "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
        "<a style='cursor: pointer;' onmouseover='dict_descriptions[\"Turnin\"] = \"" +
        "<table>" +
        "<tr><td width=65>Tactics:</td><td width=40>" + (parseFloat(statsTable.rows[6].cells[1].textContent)-65).toFixed(2) + "</td><td>65</td></tr>" +
        "<tr><td>Hit Acc:</td><td>" + (parseFloat(statsTable.rows[7].cells[1].textContent)-70).toFixed(2) + "</td><td>70</td></tr>" +
        "<tr><td>Maneuver:</td><td>" + (parseFloat(statsTable.rows[8].cells[1].textContent)-65).toFixed(2) + "</td><td>65</td></tr>" +
        "<tr><td>Weaponry:</td><td>" + (parseFloat(statsTable.rows[9].cells[1].textContent)-40).toFixed(2) + "</td><td>40</td></tr>" +
        "<tr><td>Eng:</td><td>" + (parseFloat(statsTable.rows[10].cells[1].textContent)-33).toFixed(2) + "</td><td>33</td></tr>" +
        "</table>" +
        "\"; tip(this,\"Turnin\",\"Turn-In\", \"r\");' onmouseout='nukeTip();' onclick='return false;'>" +
        "<font color='#ffcc11'>T</font></a>";
    //statsTable.rows[5].cells[0].innerHTML = statusStrOld;
}

function setupNPCCombat()
{
    var navTimeDiv = document.createElement("div");
    navTimeDiv.innerHTML = '<div style="width:100%;">' +
        '<table border="0" width="250px" align="center" style="font-size:11px;">' +
        '<tr>' +
        '<td>Time: <span id="tim">08:13:55</span></td>' +
        '<td>GMT: <span id="gmt">06:13:55</span></td>' +
        '<td>AP: <span id="ap">00:04:04</span></td>' +
        '</tr>' +
        '</table>' +
        '</div>';

    var divs = document.body.getElementsByTagName("div");
    //divs[0].insertBefore(navTimeDiv, divs[0].childNodes[13]);
    divs[0].childNodes[11].innerHTML += '&nbsp;&nbsp;<span style="font-size:10;">(AP: <span id="ap">00:04:04</span>)</span>';
    //var insertion = tables[2].previousSibling;
    //insertion.insertBefore(navTimeDiv, insertion.childNodes[0]);

    StartClock();
}

function setupDocked()
{
    var tables = document.body.getElementsByTagName("table");
    var logCell = document.createElement("td");
    logCell.colSpan = 4;
    logCell.align = "center";
    logCell.innerHTML = '<table border="0" width="500px" align="center" style="font-size:11px;">' +
        '<tr>' +
        '<td>Time: <span id="tim">08:13:55</span></td>' +
        '<td>GMT: <span id="gmt">06:13:55</span></td>' +
        '<td>AP: <span id="ap">00:04:04</span></td>' +
        '<td>B: <span id="bui">03:11:04</span></td>' +
        '<td>P: <span id="pl">01:11:04</span></td>' +
        '<td>S: <span id="sb">02:11:04</span></td>' +
        '</tr>' +
        '</table>'
    var logRow = document.createElement("tr");
    logRow.vAlign = "center";
    logRow.appendChild(logCell);
    tables[2].childNodes[0].insertBefore(logRow, tables[2].rows[0]);

    StartClock();
}

function setupShortcuts()
{
    window.addEventListener('keypress', function(e) {
        var c;
        var target;
        var altKey;
        var ctrlKey;
        if (window.event != null) {
            c = String.fromCharCode(window.event.keyCode).toUpperCase();
            altKey = window.event.altKey;
            ctrlKey = window.event.ctrlKey;
        }
        else {
            c = String.fromCharCode(e.charCode).toUpperCase();
            altKey = e.altKey;
            ctrlKey = e.ctrlKey;
        }
	
        if (window.event != null)
            target = window.event.srcElement;
        else
            target = e.originalTarget;
	
        if (target.nodeName.toUpperCase() != 'INPUT' && target.nodeName.toUpperCase() != 'TEXTAREA' && !altKey && !ctrlKey) {
            settings.shortcutCollection().actOnKey(c);
        }
        //e.stopPropagation();
        return false;
    }, true);
	
    //document.body.getElementsByTagName("table")[0].onclick = function(e){alert("hi");};
}

function setStatSwitch(element)
{
    var tbl = element.parentNode.parentNode.parentNode.parentNode;
    var view = settings.pilotAsp.skillView.get();
    element.selectedIndex = view;
    document.getElementById("resetAspButton").style.visibility = "hidden";
    var totalAspDay = settings.pilotAsp.totalAspPerDay();
    switch(view)
    {
        case 0: //actual
            tbl.rows[6].cells[2].innerHTML = settings.pilot.tac.actual;
            tbl.rows[7].cells[2].innerHTML = settings.pilot.hit.actual;
            tbl.rows[8].cells[2].innerHTML = settings.pilot.man.actual;
            tbl.rows[9].cells[2].innerHTML = settings.pilot.wep.actual;
            tbl.rows[10].cells[2].innerHTML = settings.pilot.eng.actual;
            break;
        case 1: //overskill
            tbl.rows[6].cells[2].innerHTML = settings.pilot.tac.overskillDist()+" ("+settings.pilot.tac.overskill()+")";
            tbl.rows[7].cells[2].innerHTML = settings.pilot.hit.overskillDist()+" ("+settings.pilot.hit.overskill()+")";
            tbl.rows[8].cells[2].innerHTML = settings.pilot.man.overskillDist()+" ("+settings.pilot.man.overskill()+")";
            tbl.rows[9].cells[2].innerHTML = settings.pilot.wep.overskillDist()+" ("+settings.pilot.wep.overskill()+")";
            tbl.rows[10].cells[2].innerHTML = settings.pilot.eng.overskillDist()+" ("+settings.pilot.eng.overskill()+")";
            break;
        case 2: //turnin
            tbl.rows[6].cells[2].innerHTML = settings.pilot.tac.turninDist()+" ("+settings.pilot.tac.turnin+")";
            tbl.rows[7].cells[2].innerHTML = settings.pilot.hit.turninDist()+" ("+settings.pilot.hit.turnin+")";
            tbl.rows[8].cells[2].innerHTML = settings.pilot.man.turninDist()+" ("+settings.pilot.man.turnin+")";
            tbl.rows[9].cells[2].innerHTML = settings.pilot.wep.turninDist()+" ("+settings.pilot.wep.turnin+")";
            tbl.rows[10].cells[2].innerHTML = settings.pilot.eng.turninDist()+" ("+settings.pilot.eng.turnin+")";
            break;
        case 3: //asp
            document.getElementById("resetAspButton").style.visibility = "";
            tbl.rows[6].cells[2].innerHTML = settings.pilotAsp.tac.aspGain()+" ("+(settings.pilotAsp.apUsedPerDay()*settings.pilotAsp.tac.aspGain()).toFixed(2)+")";
            tbl.rows[7].cells[2].innerHTML = settings.pilotAsp.hit.aspGain()+" ("+(settings.pilotAsp.apUsedPerDay()*settings.pilotAsp.hit.aspGain()).toFixed(2)+")";
            tbl.rows[8].cells[2].innerHTML = settings.pilotAsp.man.aspGain()+" ("+(settings.pilotAsp.apUsedPerDay()*settings.pilotAsp.man.aspGain()).toFixed(2)+")";
            tbl.rows[9].cells[2].innerHTML = settings.pilotAsp.wep.aspGain()+" ("+(settings.pilotAsp.apUsedPerDay()*settings.pilotAsp.wep.aspGain()).toFixed(2)+")";
            tbl.rows[10].cells[2].innerHTML = settings.pilotAsp.eng.aspGain()+" ("+(settings.pilotAsp.apUsedPerDay()*settings.pilotAsp.eng.aspGain()).toFixed(2)+")";
            tbl.rows[6].cells[2].title = totalAspDay;
            tbl.rows[7].cells[2].title = totalAspDay;
            tbl.rows[8].cells[2].title = totalAspDay;
            tbl.rows[9].cells[2].title = totalAspDay;
            tbl.rows[10].cells[2].title = totalAspDay;
            break;
    }
}


function showFilled(value)
{
    if(isNaN(value)) value = 0;
    return (value > 9) ? "" + value : "0" + value;
    //return value;
}

function setTime(id, value)
{
    var e = document.getElementById(id);
    if(e)
    {
        e.innerHTML = value;
    }
}

function StartClock()
{
    TheTime = new Date;
    var gmtHours = TheTime.getTimezoneOffset() / 60;

    setTime("tim", showFilled(TheTime.getHours() % 24) + ":" + showFilled(TheTime.getMinutes()) + ":" + showFilled(TheTime.getSeconds()));
    setTime("gmt", showFilled((TheTime.getHours()+gmtHours) % 24) + ":" + showFilled(TheTime.getMinutes()) + ":" + showFilled(TheTime.getSeconds()));
    setTime("ap", showFilled(0) + ":" + showFilled(5-TheTime.getMinutes() % 6) + ":" + showFilled(59-TheTime.getSeconds()));

    if(TheTime.getSeconds() == 0)
    {
        //alert(maxAPMinLeft);
        maxAPMinLeft--;
    }
    setTime("maxAP", showFilled(Math.floor(maxAPMinLeft / 60)) + ":" + showFilled(maxAPMinLeft - ((Math.floor(maxAPMinLeft / 60)) * 60)) + ":" + showFilled(59-TheTime.getSeconds()));

    var x = TheTime.getMinutes() - 25;
    if (x < 0)
    {
        x = x + 60;
        TheTime.setHours(TheTime.getHours()-1);
    }

    TheTime.setMinutes(x);
    //TheTime.setHours((TheTime.getHours() + gmtHours - (-dst) + 3));
    TheTime.setHours((TheTime.getHours() + gmtHours - 1));

    setTime("bui", showFilled( 5-(TheTime.getHours()%6)) + ":" + showFilled(59-TheTime.getMinutes() ) + ":" + showFilled(59-TheTime.getSeconds()));
    setTime("pl", showFilled( 2-((TheTime.getHours()-1+3)%3)) + ":" + showFilled(59-TheTime.getMinutes() ) + ":" + showFilled(59-TheTime.getSeconds()));
    setTime("sb", showFilled( 2-((TheTime.getHours()-2+3)%3)) + ":" + showFilled(59-TheTime.getMinutes() ) + ":" + showFilled(59-TheTime.getSeconds()));

    window.setTimeout(StartClock, 1000);
}
